package cn.exlu.wxcall.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.exlu.wxcall.R;

public class UserInfoAdapter extends ArrayAdapter<UserInfo>{
	private int resourceId;
	public UserInfoAdapter(Context context,
			int textViewResourceId, List<UserInfo> objects) {
		super(context, textViewResourceId, objects);
		resourceId = textViewResourceId;
	}

	


	int totalHeight = 0;
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view;
		ListView listView = (ListView)parent;
		if(convertView == null){
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
		}else{
			view = convertView;
		}
		
		
	     for (int i = 0, len = getCount(); i < len; i++) {   //listAdapter.getCount()返回数据项的数目
	
	         view.measure(0, 0);  //计算子项View 的宽高
	         totalHeight += view.getMeasuredHeight();  //统计所有子项的总高度
	     }

	     ViewGroup.LayoutParams params = listView.getLayoutParams();
	     params.height = totalHeight + (listView.getDividerHeight() * (getCount() - 1));
	     //listView.getDividerHeight()获取子项间分隔符占用的高度
	     //params.height最后得到整个ListView完整显示需要的高度
	     listView.setLayoutParams(params);
		

			ImageView imgViewPic = (ImageView) view.findViewById(R.id.itemImgViewPic);
			TextView txtUserinfo = (TextView) view.findViewById(R.id.itemTxtUserinfo);
			UserInfo userinfo = getItem(position);
			
			int targetW = 200;
		    int targetH = 200;

		    // Get the dimensions of the bitmap
		    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		    bmOptions.inJustDecodeBounds = true;
		    BitmapFactory.decodeFile(userinfo.getUserPic(), bmOptions);
		    int photoW = bmOptions.outWidth;
		    int photoH = bmOptions.outHeight;

		    // Determine how much to scale down the image
		    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

		    // Decode the image file into a Bitmap sized to fill the View
		    bmOptions.inJustDecodeBounds = false;
		    bmOptions.inSampleSize = scaleFactor;
		    bmOptions.inPurgeable = true;

		    Bitmap bitmap = BitmapFactory.decodeFile(userinfo.getUserPic(), bmOptions);
		    imgViewPic.setImageBitmap(bitmap);
		    
		    StringBuilder sb = new StringBuilder();
		    sb.append("姓名：").append(userinfo.getUserName()).append("\n");
		    sb.append("手机号：").append(userinfo.getUserPhone());
		    txtUserinfo.setText(sb.toString());
		
		
		
		return view;
	}

}
